package com.xym.web.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xym.pojo.Item;
import com.xym.pojo.ItemDesc;

@Service
public class ItemService {

	//后台基本路径
	@Value("${MANAGE_BASE_URL}")
	public String MANAGE_BASE_URL;
	
	@Value("${Item_DESC_PATH}")
	public String Item_DESC_PATH;
	
	@Value("${Item_PATH}")
	public String Item_PATH;
	
	//商品的redis key
	@Value("${REDIS_ITEM_KEY}")
	public String REDIS_ITEM_KEY;
	
	@Value("${REDIS_ITEM_CAT_AKK_TIME}")
	public Integer REDIS_ITEM_CAT_AKK_TIME;
	
	@Autowired
	public RedisService redisService;
	
	@Autowired
	public ApiService apiService;
	
	public Item queryItem(Long itemId) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		
		//读取缓存数据
		try {
			String item_redis = redisService.get(REDIS_ITEM_KEY+itemId);
			if(item_redis!=null){
				return mapper.readValue(item_redis, Item.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		String  itemDesc = apiService.doGet(MANAGE_BASE_URL+Item_PATH+itemId);
		Item item = mapper.readValue(itemDesc, Item.class);
		item.setImages(item.getImage().split(","));
		
		//数据存入缓存
		try {
			redisService.set(REDIS_ITEM_KEY+itemId, mapper.writeValueAsString(item), REDIS_ITEM_CAT_AKK_TIME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return item;
	}
	
	public ItemDesc queryItemDesc(Long itemId) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		//读取缓存数据
				try {
					String item_redis = redisService.get(REDIS_ITEM_KEY+"DESC"+itemId);
					if(item_redis!=null){
						return mapper.readValue(item_redis, ItemDesc.class);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
		
		
		String  itemDescjson = apiService.doGet(MANAGE_BASE_URL+Item_DESC_PATH.replace("{id}", itemId+""));
		ItemDesc itemDesc = mapper.readValue(itemDescjson, ItemDesc.class);
		
		//缓存数据的存储
		try {
			redisService.set(REDIS_ITEM_KEY+"DESC"+itemId, mapper.writeValueAsString(itemDesc), REDIS_ITEM_CAT_AKK_TIME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return itemDesc;
	}

}
